﻿using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.NumberRules.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.NumberRules.Services
{
    public class DocumentNumberRuleManager : DomainService
    {
        private IGuidGenerator _guidGenerator;
        private IDocumentNumberRuleRepository _repository;

        public DocumentNumberRuleManager(IGuidGenerator guidGenerator, IDocumentNumberRuleRepository repository)
        {
            _guidGenerator = guidGenerator;
            _repository = repository;
        }

        public async Task<DocumentNumberRule> GetAsync(Guid? id , string name , DocumentType? type , string prefix , int flowLength)
        {
            DocumentNumberRule numberRule;

            if (id.HasValue)
            {
                numberRule = await _repository.GetAsync(id.Value);

                if (numberRule == null)
                    throw new UserFriendlyException($"单据编码规则:{id.Value}不存在");

                numberRule.Change(name, prefix, flowLength);
            }
            else
                numberRule = new DocumentNumberRule(_guidGenerator.Create(), type.Value, name, prefix, flowLength);

            return numberRule;
        }

        public async Task<List<DocumentNumberRule>> SetDefaultRuleAsync(DocumentNumberRule numberRule)
        {
            //保证默认只有一个
            var numberRules = await _repository.GetListAsync(numberRule.Type, true);

            numberRules = numberRules.Where(x => x.Id != numberRule.Id).ToList();

            numberRule.SetDefault(true);

            numberRules.ForEach(x => x.SetDefault(false));

            return numberRules;
        }
    }
}
